package com.wwz.service;

import com.alibaba.fastjson.JSONObject;
import com.wwz.config.RabbitSender;
import com.wwz.config.RedisLuaTemplate;
import com.wwz.dao.OrderDao;
import com.wwz.feign.ProductFeign;
import com.wwz.feign.UserFeign;
import com.wwz.tcc.TccOrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class OrderServiceImpl implements OrderService{
    Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private OrderDao orderDao;

    @Autowired
    private ProductFeign productFeign;
    @Autowired
    private UserFeign userFeign;
    @Autowired
    private OrderService orderService;
@Autowired
private TccOrderService tccOrderService;
/*@Autowired
private RabbitSender rabbitSender;*/
@Autowired
private RedisLuaTemplate redisLuaTemplate;
    @Resource(name="masterStringRedisTemplate")
    private StringRedisTemplate stringRedisTemplate;

  /*  @GlobalTransactional*/
    @Override
    public Integer insert(){
        long branchId  = System.currentTimeMillis();
        String id = stringRedisTemplate.opsForValue().get("order:keyprefix:orderId");
        if(!org.apache.commons.lang3.StringUtils.isEmpty(id)&&Integer.parseInt(id)>=1000){
            return 0;
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("name","5");
        jsonObject.put("branch_id",branchId);
        jsonObject.put("num",5);
        try{
            if(!redisLuaTemplate.increment("orders:keyprefix:orderId",jsonObject.toJSONString(),"order:keyprefix:"+branchId,-1,"10000000")){
                return 0;
            };
        }catch (Exception e){
            e.printStackTrace();
            if(!redisLuaTemplate.incrementBySlave("orders:keyprefix:orderId",jsonObject.toJSONString(),"order:keyprefix:"+branchId,-1,"10000000")){
                return 0;
            };
        }

       // rabbitSender.sendMessage(3L,60000);
      /*  long branchId = System.currentTimeMillis();{
            return 0;
        }
        int i =  tccOrderService.insert(null,"44",branchId);
        userFeign.insert("333",branchId);
        productFeign.update("333",branchId);*/
        return 1;
    }


    public String nofFound(){
        return "404";
    }

}
